package zzps.exeed.web.handle;

import zzps.exeed.kernel.core.PandaContainer;
import zzps.exeed.kernel.core.PandaEmbryo;
import zzps.exeed.kernel.holder.MethodHolder;
import zzps.exeed.kernel.holder.PandaHolder;
import zzps.exeed.kernel.pandabuilder.PandaBuilder;
import zzps.exeed.kernel.tool.StrTool;
import zzps.exeed.web.annotation.Controller;
import zzps.exeed.web.annotation.Mapping;
import zzps.exeed.web.http.HttpMethod;
import zzps.exeed.web.route.Route;

import java.lang.reflect.Method;
import java.util.function.Consumer;

public class ControllerPandaBuilder implements PandaBuilder<Controller> {

    @Override
    public void collect(Class<?> target, Controller annotation, Consumer<PandaEmbryo> consumer) {
        PandaEmbryo<Controller> pandaEmbryo = new PandaEmbryo(null,target, annotation,this);
        consumer.accept(pandaEmbryo);
    }

    @Override
    public void build(PandaEmbryo<Controller> pandaEmbryo, Consumer<PandaHolder> consumer, PandaContainer pandaContainer) {
        Class<?> clazz = pandaEmbryo.clazz();
        PandaHolder pandaHolder = new PandaHolder(clazz);
        consumer.accept(pandaHolder);
        Mapping clazzMapping = clazz.getAnnotation(Mapping.class);
        String basePath = "";
        HttpMethod[] baseHttpMethods = { };
        if (clazzMapping != null){
            basePath = clazzMapping.path();
            baseHttpMethods = clazzMapping.method();
        }
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            Mapping methodMapping = method.getAnnotation(Mapping.class);
            if (methodMapping != null){
                if (StrTool.isEmpty(methodMapping.path())){
                    continue;
                }
                String path = StrTool.isEmpty(basePath)?methodMapping.path() : basePath+"/"+methodMapping.path();
                HttpMethod[] httpMethod = methodMapping.method() == null?baseHttpMethods : methodMapping.method();
                MethodHolder methodHolder = new MethodHolder(pandaHolder, method);
                Action action = new Action(pandaHolder, methodHolder);
                Route route = new Route(path, httpMethod, action);
                HandlerManager.get().addRoute(route);
            }
        }
    }
}
